//
//  FeedbackViewController.m
//  quanminzhekou
//
//  Created by zxl on 15/1/8.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "FeedbackViewController.h"
#import "UMFeedback.h"

@interface FeedbackViewController () <UMFeedbackDataDelegate, UIAlertViewDelegate>

@end

@implementation FeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.countLab.text = [NSString stringWithFormat:@"%zd", self.textView.text.length];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)dealloc
{
    [UMFeedback sharedInstance].delegate = nil;
}

- (void)showAlertViewWithTitle:(NSString*)title andMessage:(NSString*)message andDelegate:(id)delegate {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:@"知道了！" otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark - IBAction
- (IBAction)onTapBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onTapSendBtn:(id)sender {
    self.sendBtn.enabled = NO;
    
    if (![self.textView.text isKindOfClass:[NSString class]] || 0 == self.textView.text.length) {
        [self showAlertViewWithTitle:@"反馈错误" andMessage:@"反馈信息内容不能为空！" andDelegate:nil];
        self.sendBtn.enabled = YES;
    } else {
        [UMFeedback sharedInstance].delegate = self;
        [[UMFeedback sharedInstance] post:@{@"content": self.textView.text}];
    }
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    self.countLab.text = [NSString stringWithFormat:@"%zd", textView.text.length];
    return YES;
}

#pragma mark - UMFeedbackDataDelegate
- (void)postFinishedWithError:(NSError *)error {
    if (error != nil) {
        if (1000 == error.code) {
            [self showAlertViewWithTitle:@"反馈错误" andMessage:@"请检查您的网络设置！" andDelegate:nil];
        } else {
            [self showAlertViewWithTitle:@"反馈错误" andMessage:[NSString stringWithFormat:@"%@", error.localizedDescription] andDelegate:nil];
        }
        self.sendBtn.enabled = YES;
    } else {
        [self showAlertViewWithTitle:@"反馈成功" andMessage:@"感谢您提出的宝贵意见，我们会尽快为您解决！" andDelegate:self];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
